package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.rabbitmq.config.RabbitConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import sun.plugin2.message.Message;

import java.util.Date;
import java.util.List;

/**
 * @Auther 赵乾坤
 * @Date 2021-01-13 0:23
 * 秒杀监听
 */
@Component
public class SeckillConsumer {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = RabbitConst.QUEUE_TASK_1,durable = "true",autoDelete = "false"),
                    exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_TASK),
            key=RabbitConst.ROUTING_TASK_1
            )
    })
    public void receicerMessage(Message message, Channel channel) throws Exception {
        //将DB中数据压入缓存中
        //1:查询DB中数据  当天数据
        //  -- 当前
        // -- 审核通过的
        // --  还有库存的
        List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(new QueryWrapper<SeckillGoods>()
                .eq("status", "1").gt("stock_count", 0)
                .eq("DATE_FORMAT(start_time,'%Y-%m-%d')", DateUtil.formatDate(new Date())));


        seckillGoodsList.forEach(seckillGoods -> {
            //2:放到缓存中
            if (!redisTemplate.opsForHash().hasKey(RedisConst.SECKILL_GOODS,
                    seckillGoods.getSkuId().toString())) {
                //秒杀商品压入缓存中
                redisTemplate.opsForHash().put(RedisConst.SECKILL_GOODS,
                        seckillGoods.getSkuId().toString(),seckillGoods);
                //使用Redis防止超卖
            }
        });
    }
}
